package com.muc.plugin.handler;

import com.muc.plugin.dao.MUCDao;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.util.WebManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

/**
 * <iq id='tbRcu-10' type='set'>
 * <query xmlns='xls:muc-ungroup'>
 * <roomJid>aaaaaa</roomJid>
 * <reason>哈哈哈哈哈</reason>
 * </query>
 * </iq>
 * 解散群组
 */
public class MUCUngroupIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String MODULE_NAME = "ungroup";

    private static final String NAME_SPACE = "xls:muc-ungroup";

    private static final Logger log = LoggerFactory.getLogger(MUCUngroupIQHandler.class);

    public MUCUngroupIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        log.info("execute " + this.getClass().getName() + " method: handleIQ");
        IQ reply = IQ.createResultIQ(packet);

        Element iq = packet.getElement();
        Element query = iq.element("query");
        Element roomJid = query.element("roomJid");
        Element reason = query.element("reason");
        if (roomJid == null || reason == null) {
            reply.setError(PacketError.Condition.item_not_found);
            return reply;
        }
        MUCRoom room = new WebManager().getMultiUserChatManager().
                getMultiUserChatService("conference")
                .getChatRoom(roomJid.getText());
        if (room != null) {
            room.destroyRoom(null, reason.getText());
        }
        // 移除群组内所有群成员的群昵称数据
        MUCDao.removeGroupMembersNickname(roomJid.getText());
        reply.setType(IQ.Type.result);
        log.info("success result: " + reply.toXML());
        return reply;
    }

}
